package com.delayqueue.core.executor;

import com.delayqueue.common.enums.ExecutorType;
import com.delayqueue.common.task.Task;
import com.delayqueue.core.common.BeanHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.HashMap;

@Slf4j
@Component
public class ExecutorFactory implements BeanPostProcessor {

    private HashMap<ExecutorType, Class<? extends Executor>> map = new HashMap<>();

    @Autowired
    private BeanHelper beanHelper;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class classs = bean.getClass();
        boolean check = BeanHelper.isImplementFrom(classs, Executor.class);
        if (check) {
            String typeName = classs.getSimpleName();
            String typePrefix = typeName.substring(0, typeName.length() - "Executor".length());
            ExecutorType[] enums = ExecutorType.values();
            for (ExecutorType executorType : enums) {
                if (executorType.name().equals(typePrefix)) {
                    map.put(executorType, classs);
                }
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    public Executor getExecutor(Task task) {
        return getExecutor(task.getExecutorType());
    }

    public Executor getExecutor(ExecutorType executorType) {
        Class<? extends Executor> classs = map.get(executorType);
        Assert.notNull(classs, "未找到" + executorType + "对应的Executor");
        return beanHelper.getBean(classs);
    }
}
